﻿module Sustainalytics.Universes.Admin {

    import Common = Sustainalytics.Common;
    import CommonAdmin = Sustainalytics.Common.Admin;

    export class UniversesService implements IUniversesService {

        private $q: ng.IQService;
        private $http: ng.IHttpService;
        private notificationFactory: Common.INotificationFactory;
        private staticObjectsAdmin: CommonAdmin.IStaticObjects;
        private $location: ng.ILocationService;
        private $upload: any;

        constructor(
            $q: ng.IQService,
            $http: ng.IHttpService,
            $location: ng.ILocationService,
            notificationFactory: Common.INotificationFactory,
            staticObjectsAdmin: CommonAdmin.IStaticObjects,
            $upload) {

            this.$q = $q;
            this.$http = $http;
            this.notificationFactory = notificationFactory;
            this.staticObjectsAdmin = staticObjectsAdmin;
            this.$location = $location;
            this.$upload = $upload;
        }

        private filesUrl(): string {
            var ctx = this;
            return ctx.$location.protocol() + "://" + ctx.$location.host() + ":" + ctx.$location.port() + "/universesserv/api/v1/files";
        }

        private uploaderrorlogsUrl(): string {
            var ctx = this;
            return ctx.$location.protocol() + "://" + ctx.$location.host() + ":" + ctx.$location.port() + "/universesserv/api/v1/uploaderrorlogs";
        }

        public fileUpload(file: File, id: string): ng.IPromise<{}> {

            var ctx = this;
            var def = ctx.$q.defer();

            var reader = new FileReader();
            reader.onload = (data) => {
                return ctx.$upload.http({
                    method: (id) ? "PUT" : "POST",
                    url: ctx.filesUrl() + ((id) ? id : ""),
                    headers: { 'Content-Disposition': 'attachment; filename="' + file.name + '"', 'Content-Type': file.type, },
                    data: reader.result
                })
                    .progress(evt => { console.log('percent: ' + (100.0 * evt.loaded / evt.total)); })
                    .success((data, status, headers, config) => { def.resolve(data) });
            };
            reader.readAsArrayBuffer(file);
            return def.promise;
        }

        public getUploadErrorLogs(): ng.IPromise<Array<IUploadErrorLog>> {
            var ctx = this;
            var def = ctx.$q.defer();

            var promise = ctx.$http.get(ctx.uploaderrorlogsUrl());
            promise
                .success(data => { def.resolve(data); })
                .error(err => { ctx.showError(err); def.reject(); });
            return def.promise;
        }

        public isProcessingScheduled(): ng.IPromise<boolean> {
            var ctx = this;
            var def = ctx.$q.defer();

            var promise = ctx.$http.get(ctx.filesUrl(), { params: { isProcessing: true } });
            promise
                .success(data => { def.resolve(data); })
                .error(err => { ctx.showError(err); def.reject(); });
            return def.promise;
        }

        private showError(err) {
            var ctx = this;
            if (err && err['code'])
                ctx.notificationFactory.error('', ctx.staticObjectsAdmin.getMessageByInternalCode(err['code']));
        }
    }

    // register service with Tools Angular module
    var mod = angular.module(universesAdminModuleName);

    mod.service('UniversesService',
        ['$q', '$http', '$location', 'notificationFactory', 'staticObjectsAdmin', '$upload', UniversesService]);
}